# -*- coding: utf-8 -*-
import json
import random
import time
import requests
import logging
from traceback import format_exc
from datetime import datetime
from requests import TooManyRedirects
from zc_core.model.items import Order
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_time, parse_number

from esgcc.simple.simple_dao import SimpleDao
from esgcc.simple.simple_session import SimpleSession
from zc_core.util.encrypt_util import base64_decode

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='latest_order_list_ios.log',
    filemode='a')
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

# 登录会话管理
simple_session = SimpleSession()
# cookies = {'JSESSIONID': '5A4A65598E15B8EE363B0B3E0D0D9D1A', '__d_s_': '74DB46A51500E46F323D8DD2DA3ADE8A', '__s_f_c_s_': '10AC30904622FD37BB2A5AE8319A49EB', '__t_c_k_': 'cd701743086843f686db3c44e5994509'}
cookies = {}

# 构建校验器对象
# settings = get_project_settings()
# proxy_pool = CachedProxyPool(settings)
simple_dao = SimpleDao()


def send_req():
    order_list_url = 'http://m.esgcc.com.cn/common/sendPostByJsonStr'
    headers = {
        'Host': 'm.esgcc.com.cn',
        'Accept': 'application/json',
        'path': '/newmmainapi/mmain/ShowIndexService/getLatestOrdersForHomePage',
        'Accept-Language': 'zh-cn',
        'Accept-Encoding': 'gzip, deflate',
        'type': 'getUserData',
        'token': '5fcda814427f74a0a8792dfad6759f01',
        'User-Agent': 'e%E9%80%89%E8%B4%AD/2.3.5 CFNetwork/976 Darwin/18.2.0',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json',
        'Cookie': '__d_s_=334D0297D60B121D8BE0CF1C6767CF19; __s_f_c_s_=DD938D519F34AF09CF87372D7FA98041; JSESSIONID=402BD8C372FB166169EEE1B5BBC34BB2',
    }
    try:
        # 登录获取cookie
        # cookies = simple_session.get_cookies()
        rs = requests.post(
            url=order_list_url,
            cookies=cookies,
            headers=headers,
            data='{}',
            timeout=45
        )
        return rs.text
    except TooManyRedirects as ex:
        logging.info('--> logout: %s' % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        simple_session.clean_cookies()


def parse_order_list_ios(txt):
    order_list = list()
    ex_data = json.loads(txt).get('exData', '').replace('\n', '')
    str_decode = base64_decode(base64_decode(ex_data))
    data = json.loads(str_decode).get('resultDTO', {}).get('data', {})
    if data:
        orders = data.get('list', [])
        if orders:
            for order in orders:
                order_id = order.get('orderId')
                order_dept = order.get('companyName')
                order_time = parse_time(order.get('orderTime'))
                total_count = parse_number(order.get('amount'))
                total_amount = parse_number(order.get('paymentAmount'))
                sp_name = order.get('supplierName')
                order_user = order.get('loginAccount')
                page = Order()
                page['_id'] = order_id
                page['url'] = 'http://buser.esgcc.com.cn/order/recent_purchase_detail?orderId={}'.format(order_id)
                page['orderTime'] = order_time
                page['orderDept'] = order_dept
                page['totalPrice'] = total_amount
                page['totalCount'] = total_count
                page['supplierName'] = sp_name
                page['orderUser'] = order_user
                page['batchNo'] = time_to_batch_no(order_time)
                page['genTime'] = datetime.utcnow()
                order_list.append(page)
    else:
        raise Exception('need to retry...')

    return order_list


def work():
    try:
        logging.info('采集: %s' % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        txt = send_req()
        order_list = parse_order_list_ios(txt)
        simple_dao.save_orders(order_list)
        logging.info('数量: %s' % len(order_list))
    except Exception as e:
        logging.info(format_exc())
        _ = e


if __name__ == '__main__':
    while True:
        work()
        time.sleep(random.randint(50, 80))
